package cn.hrbnu.service.impl;

import cn.hrbnu.mapper.ArticleMapper;
import cn.hrbnu.po.Category;
import cn.hrbnu.service.CategoryService;
import cn.hrbnu.util.ResponseResult;
import cn.hrbnu.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import cn.hrbnu.mapper.CategoryMapper;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;

    private final ArticleMapper articleMapper;

    public CategoryServiceImpl(CategoryMapper categoryMapper, ArticleMapper articleMapper) {
        this.categoryMapper = categoryMapper;
        this.articleMapper = articleMapper;
    }

    @Override
    public ResponseResult<Object> getCategoryList() {
        //先去查询所有分类
        List<Category> categoryList = categoryMapper.selAll();
        //创建一个列表用于存储转换后的分类信息
        List<CategoryVo> categoryVos = new ArrayList<>();
        //再去查询分类有没有文章

        //遍历所有分类，检查每个分类下是否有文章
        for (Category category : categoryList) {
            //查询当前分类下文章的数量
            Long count = articleMapper.selCountByCategoryId(category.getId());
            //如果当前分类下有文章，则创建一个CategoryVo对象，并将分类信息复制到该对象中
            if (count > 0) {
                CategoryVo categoryVo = new CategoryVo();
                BeanUtils.copyProperties(category, categoryVo);
                //将含有文章的分类信息添加到列表中
                categoryVos.add(categoryVo);
            }
        }

        //返回包含所有含有文章的分类信息的响应结果
        return new ResponseResult<>(200,"操作成功",categoryVos);
    }

}
